package io.renren.modules.tag.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SqlGenerator {

    public static void main(String[] args) {
        Map<String, String> tagSubjectMap = new HashMap<>();
        tagSubjectMap.put("青年", "ztk_ryztxxb");
        tagSubjectMap.put("境外旅游", "ztk_ryztxxb");
        tagSubjectMap.put("频繁出行", "ztk_ryztxxb");
        tagSubjectMap.put("去往敏感地", "ztk_ryztxxb");

        List<String> tags = new ArrayList<>();
        tags.add("青年");
        tags.add("境外旅游");
        tags.add("频繁出行");
        tags.add("去往敏感地");

        String sql = generateSql(tagSubjectMap, tags);
        System.out.println(sql);
    }

    public static String generateSql(Map<String, String> tagSubjectMap, List<String> tags) {
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("WITH (");

        for (int i = 0; i < tags.size(); i++) {
            String tag = tags.get(i);
            String subject = tagSubjectMap.get(tag);

            if (subject == null) {
                throw new IllegalArgumentException("No subject found for tag: " + tag);
            }

            sqlBuilder.append("(SELECT tagbitmap FROM (SELECT * FROM labelinfo.label_tag_bitmap_all WHERE subject = '")
                      .append(subject)
                      .append("') WHERE tagvalue = '")
                      .append(tag)
                      .append("') AS tag")
                      .append(i + 1);

            if (i < tags.size() - 1) {
                sqlBuilder.append(", ");
            }
        }

        sqlBuilder.append(") SELECT bitmapToArray(bitmapOr(");

        for (int i = 0; i < tags.size(); i += 2) {
            sqlBuilder.append("bitmapAnd(tag")
                      .append(i + 1)
                      .append(", tag")
                      .append(i + 2)
                      .append(")");

            if (i < tags.size() - 2) {
                sqlBuilder.append(", ");
            }
        }

        sqlBuilder.append(")) AS customer");

        return sqlBuilder.toString();
    }

}
